package model.core;

import java.util.LinkedList;
import java.util.Queue;

import model.mediators.TerminalMediator;

/**
 * Logger class is used to gather the information to output to the user.
 */
public class Logger {
	private static Logger instance;
	private static Queue<String> buffer;
	private static int bufferLength;	// number of chars to be displayed per line - will depend on GUI
	
	/**
	 * Return the game's logger.  This is the only method you should
	 * use to access the logger.  Note that the default buffer is of 
	 * length 100.  If you want a different length buffer, use the
	 * setBufferLength() method.
	 * @return
	 */
	public static Logger getInstance(){
		return instance;
	}
	
	/**
	 * Constructor for the Logger.
	 * @param bufferLength
	 * @param viewer
	 */
	public Logger(int width){
		bufferLength = width;
		buffer = new LinkedList<String>();
		instance = this;
		
	}
	
	/**
	 * Set the buffer length (use this only if you need a different
	 * buffer length than the default).
	 * @param length
	 */
	public void setBufferLength(int length){
		bufferLength = length;
	}
	
	/**
	 * This method writes information to the logger's
	 * output buffer.
	 * @param string
	 */
	public void writeToLogger(String string){
		if(string.length() <= bufferLength)
			buffer.add(string);
		else
			addSeveralStringsToQueue(string);
	}
	
	/**
	 * Helper method for writeToLogger which handles adding 
	 * a string that is longer than the buffer length to the
	 * buffer queue.
	 * @param string
	 */
	private void addSeveralStringsToQueue(String string){
		int length = string.length();
		int i = 0;
		// partition the string into substrings of length bufferLength
		// and add those to the bufferQueue
		for(;length > bufferLength;length-=bufferLength, i+=bufferLength)
			buffer.add(string.substring(i,i+length-1));
		// add any remaining portion of the string to the bufferQueue
		if(length % bufferLength != 0)
			buffer.add(string.substring(i,length - 1));
	}
	
	/**
	 * This method reads a String from the buffer.  This 
	 * string will be displayed in the GUI's console.
	 * @return
	 */
	public static String readFromLogger(){
		return buffer.isEmpty() ? null : buffer.remove();
	}
}
